<!-- 学生注册 -->

<template>
  <div class="register-container">
    <div class="register-card">
      <div class="avatar-wrapper">
        <img src="@/assets/images/arrage.png" alt="Logo"/>
      </div>
      <h2 class="form-title">学生注册</h2>
      <el-form
          ref="regFormRef"
          :model="studentRegForm"
          :rules="studentRegRules"
          class="register-form"
          label-width="0"
      >
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
              v-model="studentRegForm.username"
              placeholder="请输入用户名"
              clearable
              class="register-input"
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
              v-model.trim="studentRegForm.password"
              placeholder="请输入密码"
              show-password
              class="register-input"
          />
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item prop="password2">
          <el-input
              v-model.trim="studentRegForm.password2"
              placeholder="确认密码"
              show-password
              autocomplete="off"
              class="register-input"
          />
        </el-form-item>

        <!-- 真实姓名 -->
        <el-form-item prop="realname">
          <el-input
              v-model="studentRegForm.realname"
              placeholder="请输入真实姓名"
              clearable
              class="register-input"
          />
        </el-form-item>

        <!-- 年级 -->
        <el-form-item prop="grade">
          <el-select
              v-model="studentRegForm.grade"
              placeholder="请选择年级"
              clearable
              class="register-input"
          >
            <el-option
                v-for="item in studentRegForm.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 学号 + 生成按钮 -->
        <el-form-item prop="studentNo">
          <div class="studentNo-wrapper">
            <el-input
                v-model="studentRegForm.studentNo"
                placeholder="点击右侧按钮生成学号"
                disabled
                class="register-input"
            />
            <el-button
                class="generate-btn"
                type="primary"
                @click="createStuNo"
            >创建学号
            </el-button>
          </div>
        </el-form-item>

        <!-- 联系电话 -->
        <el-form-item prop="telephone">
          <el-input
              v-model="studentRegForm.telephone"
              placeholder="联系电话"
              clearable
              class="register-input"
          />
        </el-form-item>

        <!-- 电子邮件 -->
        <el-form-item prop="email">
          <el-input
              v-model="studentRegForm.email"
              placeholder="电子邮件"
              clearable
              class="register-input"
          />
        </el-form-item>

        <!-- 家庭住址 -->
        <el-form-item prop="address">
          <el-input
              v-model="studentRegForm.address"
              placeholder="家庭住址"
              clearable
              class="register-input"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="btn-group">
          <el-button type="primary" @click="register">注册</el-button>
          <el-button type="info" @click="hasNo">已有账号</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>


<script setup>
import {ref, reactive, onMounted, getCurrentInstance, nextTick} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {useStore} from 'vuex';

const {proxy} = getCurrentInstance();
const store = useStore();
const router = useRouter();


const studentRegForm = ref({
  studentNo: "",
  username: "",
  password: "",
  password2: "",
  realname: "",
  telephone: "",
  address: "",
  email: "",
  options: [
    {
      value: "01",
      label: "高一",
    },
    {
      value: "02",
      label: "高二",
    },
    {
      value: "03",
      label: "高三",
    },
  ],
  grade: "",
  gradeName: "",
});

var validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (studentRegForm.value.password !== "") {
      proxy.$refs.regFormRef.validateField("password2");
    }
    callback();
  }
};
var validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== studentRegForm.value.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
};

const studentRegRules = ref({
  username: [
    {required: true, message: "请输入账号", trigger: "blur"},
    {
      min: 3,
      max: 15,
      message: "长度在 3 到 15 个字符",
      trigger: "blur",
    },
  ],
  password: [
    {required: true, message: "请输入密码", trigger: "blur"},
    {validator: validatePass, trigger: "blur"},
    {
      min: 6,
      max: 15,
      message: "长度在 6 到 15 个字符",
      trigger: "blur",
    },
  ],
  password2: [
    {required: true, message: "请确认密码", trigger: "blur"},
    {validator: validatePass2, trigger: "blur"},
    {
      min: 6,
      max: 15,
      message: "长度在 6 到 15 个字符",
      trigger: "blur",
    },
  ],
  studentNo: [
    {required: true, message: "请先给自己申请个学号", trigger: "blur"},
  ],
  email: [{required: true, message: "请输入邮件", trigger: "blur"}],
});


const handleSelectChange = (v) => {
  proxy.studentRegForm.options.map((k) => {
    if (k.value === v) {
      proxy.studentRegForm.gradeName = k.label;
      return;
    }
  });
}

function hasNo() {
  // 已经有账号，跳转到登录界面
  router.push({
    name: 'login'
  })
}

const createStuNo = async () => {
  // 验证是否选择了年级
  if (!studentRegForm.value.grade) {
    ElMessage({
      message: "请先选择年级",
      type: 'warning'
    });
    return;
  }

  try {
    const uid = await proxy.$api.createStudentNo(studentRegForm.value.grade);
    console.log(uid,"请求学号的响应")
    if (uid) {
      studentRegForm.value.studentNo = uid;
      ElMessage({
        message: "申请学号成功，请牢记您的学号：" + studentRegForm.value.studentNo,
        type: 'success',
      });
    } else {
      ElMessage({
        message: uid || "生成学号失败，请重试",
        type: 'error'
      });
    }
  } catch (error) {
    console.log(error,"生成学号失败");
    ElMessage({
      message: "生成学号失败，请重试",
      type: 'error'

    });
  }
}

const sanitizeStudentData = (rawData) => {
  const { password2, gradeName, options, ...cleanData } = rawData;
  return cleanData;
}

const register = async () => {
  // 使用自定义验证
  const isValid = await validateForm();
  if (isValid) {
    try {
      const response = await proxy.$api.register(sanitizeStudentData(studentRegForm.value));
      if (response) {
        alert(`注册成功，请用你的学号${response.studentNo}登录系统`);
        router.push({
          name: 'login'
        })
      } else {
        alert(response.message);
      }
    } catch (error) {
      alert("注册失败，请重试");
    }
  }
};

// 自定义验证函数
const validateForm = () => {
  return new Promise((resolve) => {
    proxy.$refs.regFormRef.validate((valid) => {
      resolve(valid);
    });
  });
};

</script>

<style lang="less" scoped>
.register-container {
  width: 100%;
  height: 100vh;
  background: linear-gradient(135deg, #a8edea, #fed6e3);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    width: 220px;
    height: 220px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    top: 12%;
    left: 14%;
  }

  &::after {
    content: '';
    position: absolute;
    width: 320px;
    height: 320px;
    background: rgba(0, 0, 0, 0.05);
    border-radius: 50%;
    bottom: 6%;
    right: 12%;
  }
}

.register-card {
  width: 560px;
  padding: 80px 32px 32px;
  background: #ffffffee;
  border-radius: 16px;
  box-shadow: 0 16px 32px rgba(0, 0, 0, 0.1);
  position: relative;
  text-align: center;
  overflow: hidden;
}

.avatar-wrapper {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 80px;
  border: 4px solid #fff;
  //border-radius: 50%;
  background: #fff;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.form-title {
  margin-top: 50px;
  font-size: 22px;
  color: #333;
  font-weight: 500;
}

.register-form {
  margin-top: 24px;

  .el-form-item {
    margin-bottom: 18px;
  }

  .register-input {
    width: 100%;
    border-radius: 8px;
    transition: border-color 0.3s;

    &:focus-within {
      .el-input__inner {
        border-color: #42caff !important;
      }
    }
  }
}

.studentNo-wrapper {
  display: flex;
  align-items: center;

  .register-input {
    flex: 1;
  }

  .generate-btn {
    margin-left: 10px;
    border-radius: 8px;
  }
}

.btn-group {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 24px;

  .el-button {
    padding: 0 36px;
    border-radius: 8px;
  }

  .el-button[type='primary'] {
    background: #42caff;
    border-color: #42caff;

    &:hover {
      background: darken(#42caff, 5%);
      border-color: darken(#42caff, 5%);
    }
  }

  .el-button[type='info'] {
    color: #42caff;
    border-color: #42caff;

    &:hover {
      background: fade(#42caff, 10%);
    }
  }
}
</style>
